<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { EdubaseSemesterWeekApi } from '#/api/edu/base/setting/semesterWeek';

import { defineProps, ref } from 'vue';

import { confirm, Page, useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart, isEmpty } from '@vben/utils';

import { message } from 'ant-design-vue';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteSemesterWeek,
  deleteSemesterWeekList,
  exportSemesterWeek,
  getSemesterWeekPage,
  initSemesterWeek,
} from '#/api/edu/base/setting/semesterWeek';
import { $t } from '#/locales';

import { useGridColumns, useGridFormSchema } from './data';
import Detail from './modules/detail.vue';
import Form from './modules/form.vue';

const props = defineProps<{
  semesterId: string;
}>();
const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

const [DetailModal, detailModalApi] = useVbenModal({
  connectedComponent: Detail,
  destroyOnClose: true,
});

/** 刷新表格 */
function handleRefresh() {
  gridApi.reload();
}
function handleInit() {
  confirm('是否确认初始化该学期的每周数据，初始化将删除之前的设置').then(
    async () => {
      const hideLoading = message.loading({
        content: '初始化中...',
        duration: 0,
      });
      try {
        await initSemesterWeek(props.semesterId);
        message.success({
          content: '初始化成功',
        });
        handleRefresh();
      } finally {
        hideLoading();
      }
    },
  );
}
/** 创建学期周次 */
function handleCreate() {
  formModalApi.setData({ semesterId: props.semesterId }).open();
}

/** 编辑学期周次 */
function handleEdit(row: EdubaseSemesterWeekApi.SemesterWeek) {
  formModalApi.setData(row).open();
}

/** 查看学期周次 */
function handleDetail(row: EdubaseSemesterWeekApi.SemesterWeek) {
  detailModalApi.setData(row).open();
}

/** 删除学期周次 */
async function handleDelete(row: EdubaseSemesterWeekApi.SemesterWeek) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.id]),
    duration: 0,
  });
  try {
    await deleteSemesterWeek(row.id as number);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.id]),
    });
    handleRefresh();
  } finally {
    hideLoading();
  }
}

/** 批量删除学期周次 */
async function handleDeleteBatch() {
  await confirm($t('ui.actionMessage.deleteBatchConfirm'));
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deletingBatch'),
    duration: 0,
  });
  try {
    await deleteSemesterWeekList(checkedIds.value);
    checkedIds.value = [];
    message.success({
      content: $t('ui.actionMessage.deleteSuccess'),
    });
    handleRefresh();
  } finally {
    hideLoading();
  }
}

const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
  records,
}: {
  records: EdubaseSemesterWeekApi.SemesterWeek[];
}) {
  checkedIds.value = records.map((item) => item.id!);
}

/** 导出表格 */
async function handleExport() {
  const data = await exportSemesterWeek(await gridApi.formApi.getValues());
  downloadFileFromBlobPart({ fileName: '学期周次.xls', source: data });
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    id: 'SemesterWeek-grid',
    columns: useGridColumns(),
    height: 'auto',
    pagerConfig: {
      enabled: true,
    },
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getSemesterWeekPage(
            {
              pageNo: page.currentPage,
              pageSize: page.pageSize,
              ...formValues,
              semesterId: props.semesterId,
            },
            false,
            false,
          );
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<EdubaseSemesterWeekApi.SemesterWeek>,
  gridEvents: {
    checkboxAll: handleRowCheckboxChange,
    checkboxChange: handleRowCheckboxChange,
  },
});
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="handleRefresh" />
    <DetailModal @success="handleRefresh" />
    <Grid table-title="学期周次列表">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: '初始化',
              type: 'primary',
              icon: ACTION_ICON.REFRESH,
              auth: ['edu:base:semester-week:create'],
              onClick: handleInit,
            },
            {
              label: $t('ui.actionTitle.create', ['学期周次']),
              type: 'primary',
              icon: ACTION_ICON.ADD,
              auth: ['edu:base:semester-week:create'],
              onClick: handleCreate,
            },
            {
              label: $t('ui.actionTitle.export'),
              type: 'primary',
              icon: ACTION_ICON.DOWNLOAD,
              auth: ['edu:base:semester-week:export'],
              onClick: handleExport,
            },
            {
              label: $t('ui.actionTitle.deleteBatch'),
              type: 'primary',
              danger: true,
              icon: ACTION_ICON.DELETE,
              disabled: isEmpty(checkedIds),
              auth: ['edu:base:semester-week:delete'],
              onClick: handleDeleteBatch,
            },
          ]"
        />
      </template>

      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: '查看',
              type: 'link',
              icon: ACTION_ICON.VIEW,
              auth: ['edu:base:semester-week:query'],
              onClick: handleDetail.bind(null, row),
            },
            {
              label: $t('common.edit'),
              type: 'link',
              icon: ACTION_ICON.EDIT,
              auth: ['edu:base:semester-week:update'],
              onClick: handleEdit.bind(null, row),
            },
            {
              label: $t('common.delete'),
              type: 'link',
              danger: true,
              icon: ACTION_ICON.DELETE,
              auth: ['edu:base:semester-week:delete'],
              popConfirm: {
                title: $t('ui.actionMessage.deleteConfirm', [row.id]),
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
